package wxwoa

import (
	// "fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

// WxIndexController serves the "/", "/ping" and "/hello".
type WxIndexController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context
	// Our UserService, it's an interface which
	// is binded from the main application.
	//Service services.UserService
}

// Get handles GET: http://localhost:8080/example/.
func (c *WxIndexController) Get() mvc.Result {
	// 01.尝试缓存 access_token
	appid := WeChatSubscriptionAppID(c.Ctx)
	appsecret := WeChatSubscriptionAppSecret(c.Ctx)
	ok, token := WxAccessToken{}.TryGetAccessToken(appid, appsecret)

	if !ok {
		c.Ctx.Application().Logger().Error("获得 access_token 失败：", token)
	} else {
		token = "恭喜您，access token 已自动取得"
	}

	// 01. 在调用微信 jssdk 的页面做好准备工作
	url := WX_SITE + "/wx"
	wxconf := WxJsapiTicket{}.Signature(c.Ctx, url)

	return mvc.View{
		Name: "wxapi/wx.index.html",
		Data: iris.Map{
			"Title":         "微信公众平台辅助",
			"AccessToken":   token,
			"Appid":         appid,
			"SiteUrl":       WX_SITE,
			"WxJssdkConfig": wxconf,
		},
	}
}

// GetPing serves
// Method:   GET
// Resource: http://localhost:8080/ping
func (c *WxIndexController) GetPing() string {
	c.Ctx.Application().Logger().Infof("abcdefg!!!!")
	return "pong"
}

// GetHello serves
// Method:   GET
// Resource: http://localhost:8080/hello
func (c *WxIndexController) GetHello() interface{} {
	return map[string]string{"message": "Hello Iris!"}
}

// BeforeActivation called once, before the controller adapted to the main application
// and of course before the server ran.
// After version 9 you can also add custom routes for a specific controller's methods.
// Here you can register custom method's handlers
// use the standard router with `ca.Router` to do something that you can do without mvc as well,
// and add dependencies that will be binded to a controller's fields or method function's input arguments.
func (c *WxIndexController) BeforeActivation(b mvc.BeforeActivation) {
	anyMiddlewareHere := func(ctx iris.Context) {
		ctx.Application().Logger().Warnf("Inside /custom_path")
		ctx.Next()
	}
	b.Handle("GET", "/custom_path", "CustomHandlerWithoutFollowingTheNamingGuide", anyMiddlewareHere)

	// or even add a global middleware based on this controller's router,
	// which in this example is the root "/":
	// b.Router().Use(myMiddleware)
}

// CustomHandlerWithoutFollowingTheNamingGuide serves
// Method:   GET
// Resource: http://localhost:8080/custom_path
func (c *WxIndexController) CustomHandlerWithoutFollowingTheNamingGuide() string {
	return "hello from the custom handler without following the naming guide"
}
